package com.zs.usc.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zs.usc.common.BusinessException;
import com.zs.usc.common.RestCode;
import com.zs.usc.entity.MenuInfo;
import com.zs.usc.entity.UserInfo;
import com.zs.usc.mapper.MenuInfoMapper;
import com.zs.usc.service.IMenuService;
import com.zs.usc.service.IRelationService;
import com.zs.usc.service.IUserService;
import com.zs.usc.vo.CurrentUserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ZS
 * @since 2021-12-11
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuInfoMapper, MenuInfo> implements IMenuService {

    @Autowired
    private MenuInfoMapper menuInfoMapper;

    @Autowired
    private IRelationService relationService;

    @Autowired
    private IUserService userService;

    @Override
    public List<MenuInfo> listMenu(CurrentUserInfo currentUser, String appCode) {
        // appCode不为空 判断用户是否有这个应用的权限
        if (StringUtils.isNotEmpty(appCode) && !relationService.hasAppPerms(currentUser.getUid(), appCode)) {
            throw new BusinessException(RestCode.ERROR_AUTH_ERROR, "无权访问应用！");
        }
        // appCode为空 查询该用户所有系统权限下的菜单
        return menuInfoMapper.listMenu(currentUser.getUid(), appCode);
    }

    @Override
    public List<MenuInfo> listMenuByUserId(String userId, String appCode) {
        // 1.判断用户是否存在----增强系统的健壮性：所有输入不可信 所有返回不可信
        UserInfo info = userService.selectOptionalById(userId).orElseThrow(() -> new BusinessException("用户不存在！"));
        // 2.listMenu（）
        CurrentUserInfo currentUserInfo = CurrentUserInfo.builder()
                .groupId(info.getGroupId())
                .uid(info.getUserId())
                .username(info.getUsername()).build();
        return this.listMenu(currentUserInfo, appCode);
    }

    @Override
    public List<String> getUserAllowMenus(CurrentUserInfo u, List<String> menuList) {
        return null;
    }
}
